from flask import Blueprint, request, jsonify
import json
from utils.db import db1
from .compan import get_data
from utils.redison import r

bp_message = Blueprint('message', __name__)


@bp_message.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        data = get_data()
        print(data)
        sql1 = """insert into message(title,content,stime,etime,priority,status,userid,type,userlist) values("%s","%s","%s","%s",%d,%d,%d,%d,"%s")""" % (
            data['title'], data['content'], data['stime'], data['etime'], int(data['priority']), int(data['status']),
            int(data['userid']), int(data['type']), data['userlist'])
        id = db1.update(sql1)
        print(sql1)
        if int(data['status']) == 2:
            for i in data['userlist']:
                sql2 = """insert into user_message(messageid,userid,status,stime) values(%d,%d,%d,'%s')""" % (
                    id, i, 1, data['stime'])
                db1.update(sql2)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        userid = request.args.get('userid')

        sql1 = """select m.*,u.status as ustatus from message as m left join user_message as u on m.id=u.messageid where m.status= 1 or m.id in (select messageid from user_message where userid = %d) order by m.priority desc """ % (
            int(userid))

        res1 = db1.findall(sql1)
        print(res1)
        mes = []
        for i in res1:
            if int(i['status']) == 1:
                i['ustatus'] = 0
                key = 'message' + str(i['id'])
                list = r.find_set(key)
                if list:
                    if userid in list:
                        i['ustatus'] = 1
            mes.append(i)

        # print(res1)
        print(mes)

        return jsonify({'code': 200, 'list': mes})
